package com.example.filepersistencetest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.RadioButton
import android.widget.SeekBar
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_shared_preferences.*

class SharedPreferencesActivity : AppCompatActivity() {
    private val TAG = "SharedPreferencesActivity"
    private var sex = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shared_preferences)

        val prefs = getPreferences(Context.MODE_PRIVATE)

        //滑动条
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener
        {
            override fun onProgressChanged(
                seekBar: SeekBar?,
                progress: Int,
                fromUser: Boolean
            ) {
                seekBarText.text = "${progress}%"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }
        })
        //按钮组
        radioGroup.setOnCheckedChangeListener { group, checkedId ->
            Log.e(TAG, "onCreate: checkedId = $checkedId R.id.radioMan = ${R.id.radioMan}", )
            sex = checkedId == R.id.radioMan
        }

        btnSaveData.setOnClickListener {
            val editer = prefs.edit()
            editer.putString("username",etUser.text.toString())
            editer.putString("userpsw",etPsw.text.toString())
            editer.putBoolean("sex",sex)
            editer.putBoolean("night_mode",switch1.isChecked)
            editer.putBoolean("no_disturb",switch2.isChecked)
            editer.putInt("vol",seekBar.progress)
            editer.apply()
            Toast.makeText(this, "保存成功！", Toast.LENGTH_SHORT).show()
        }

        btnReadData.setOnClickListener {
            //填入
            etUser.setText(prefs.getString("username", ""))
            etPsw.setText(prefs.getString("userpsw", ""))
            val sex = prefs.getBoolean("sex", true)
            if (sex) {
                radioMan.isChecked = true
            } else {
                radioWoman.isChecked = false
            }

            switch1.isChecked = prefs.getBoolean("night_mode", false)
            switch2.isChecked = prefs.getBoolean("no_disturb", false)

            seekBar.progress = prefs.getInt("vol", 0)
            seekBarText.text = "${seekBar.progress}%"


            Toast.makeText(this, "还原成功！", Toast.LENGTH_SHORT).show()

        }

    }
}